import json
import random
import threading
import time

from yiban import YiBan
import util
import config


def report(*user):
    try:
        yb = YiBan(user[0], user[1])
        yb.login()
        auth = yb.auth()
        if auth["code"] == 0:
            all_task = yb.getUncompletedList()["data"]
            if all_task is None or len(all_task) < 1:
                print("%s 没找到今天的体温上报的任务" % user[0])
            else:
                all_task_sort = util.desc_sort(all_task, "StartTime")  # 按开始时间排序
                new_task = all_task_sort[0]  # 只取一个最新的
                task_detail = yb.getTaskDetail(new_task["TaskId"])["data"]
                ex = {"TaskId": task_detail["Id"],
                      "title": "任务信息",
                      "content": [{"label": "任务名称", "value": task_detail["Title"]},
                                  {"label": "发布机构", "value": task_detail["PubOrgName"]},
                                  {"label": "发布人", "value": task_detail["PubPersonName"]}]}
                dict_form = {
                    "75462b7c9377ddf08710278eb6338087": 36 + round(random.random(), 2),  # 上午体温
                    "6ea1743a49dfc3ac0fd293cb67c8bfd3": 36 + round(random.random(), 2),  # 中午体温
                    "e8d851f72d99f9126ff7f4dd9538f6ca": 36 + round(random.random(), 2),  # 晚上体温
                    "20eec95fc715673304424213c4e0525d": ""  # 备注
                }
                submit_result = yb.submit(json.dumps(dict_form, ensure_ascii=False), json.dumps(
                    ex, ensure_ascii=False), task_detail["WFId"])
                if submit_result["code"] == 0:
                    share_url = yb.getShareUrl(submit_result["data"])["data"]["uri"]
                    print("%s 提问上报成功,访问此网站查看详情： %s" % (user[0], share_url))
                    if len(user) > 2:
                        util.notice(user[2], "上报成功", share_url)
                else:
                    print("[%s]遇到了一些错误:%s" % (task_detail["Title"], submit_result["msg"]))
                    if len(user) > 2:
                        util.notice(user[2], task_detail["Title"], submit_result["msg"])
        else:
            print("登录授权失败，请重新登录!")
            if len(user) > 2:
                util.notice(user[2], "授权失败", "请手动上报体温")
    except Exception as e:
        print("出错啦")
        print(e)
        if len(user) > 2:
            util.notice(user[2], "上报失败", "请手动上报体温")


if __name__ == '__main__':
    for user in config.users:
        thread = threading.Thread(target=report, args=user)
        thread.start()
        # report(user)
